/**
 * Copyright 2009 - Morten Udnæs
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.javabatch.fileio;

import java.util.Arrays;

/** Class to hold record buffer. Need to be a class since
 * buffer is passed as method parameter and changes content.
 * @author eco
 *
 */
public class FileBuffer {
    /** Buffer keeping the record. */
    private byte[] byteBuffer;

    /**
     * create a new buffer with content.
     * @param byteBuffer byte to fill buffer with
     */
    public FileBuffer(byte[] byteBuffer) {
        super();
        this.byteBuffer = byteBuffer;
    }

    /** create empty new buffer with content. */
    public FileBuffer() {
        this.byteBuffer = new byte[0];
    }

    /** Length of buffer. */
    public int length() {
        return byteBuffer.length;
    }

    public String toString() {
        return new String(byteBuffer);
    }

    public byte[] getBytes() {
        return byteBuffer;
    }

    /**
     * Copies part of a Buffer.
     * @param from from (and including) position in buffer
     * @param length (and including) position in buffer
     * @return
     */
    public byte[] getBytes(final int from, final int length) {
        return Arrays.copyOfRange(byteBuffer, from, from + length);
    }

    /**
     * Create byte buffer to hold both old and new array of bytes.
     * @param bytesToAdd bytes to add to buffer
     */
    public void addBytes(final byte[] bytesToAdd) {
        byte[] newBuffer = new byte[byteBuffer.length + bytesToAdd.length];

        System.arraycopy(byteBuffer, 0, newBuffer, 0, byteBuffer.length);
        System.arraycopy(bytesToAdd, 0, newBuffer, byteBuffer.length, bytesToAdd.length);

        byteBuffer = newBuffer;
    }

    public void addBytes(final byte[] bytesToAdd, final String fieldSeparator) {
        addBytes(fieldSeparator.getBytes());
        addBytes(bytesToAdd);
    }
}
